package com.itheima.reggie.common;


import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

//异常捕获
@RestControllerAdvice("com.itheima.reggie.controller")
public class GlobalExceptionHandler {
    //Duplicate entry '你好啊' for key 'idx_username
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> getExceptionHandler(SQLIntegrityConstraintViolationException e){
        String message = e.getMessage();
        //判断异常是否包含Duplicate entry
        if (message.contains("Duplicate entry")){
            String result = message.split(" ")[2];
            return R.error(result+"已存在");
        }
        return R.error("服务器繁忙,请稍后");
    }


    //自定义异常
    @ExceptionHandler(CustomerException.class)
    public R<String> getExceptionHandler(CustomerException e){
        return R.error(e.getMessage());
    }



}